package com.example.filemanager0211;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.rxjava3.functions.Consumer;

public class MainActivity extends AppCompatActivity {

    private TextView textpath;
    private ListView listpath;
    private ImageView imageback;
    private File currentParent;//系统文件父路径
    private File[] currentFiles;//父路径目录下文件集合


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();//获取控件
        rxpermissions();//为app获取权限//获取SD卡路径
        click();//条目列表点击事件
        back();//返回
    }

    private void initView() {
        //获取控件
        textpath = findViewById(R.id.text_path);
        listpath = findViewById(R.id.list_path);
        imageback = findViewById(R.id.image_back);
    }

    private void rxpermissions() {
        //如果没有设置权限，仍进行需要权限的敏感操作
        //系统会报SecurityException，会提示你进行的操作需要哪种权限
        new RxPermissions(this).request(Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                //aBoolean请求的权限是否全部同意，返回true
                //任意一个权限未同意，返回false
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Throwable {
                        if (aBoolean) {
                            //权限获取成功
                            if (Environment.getExternalStorageState()
                                    .equals(Environment.MEDIA_MOUNTED)) {//判断SD卡是否插入
                                File root = new File(Environment.getExternalStorageDirectory().getCanonicalPath());
                                currentParent = root;
                                currentFiles = root.listFiles();
                                inflateListView(currentFiles);

                            } else {
                                Toast.makeText(MainActivity.this, "SD卡未插入", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            //权限获取失败
                            Toast.makeText(MainActivity.this, "权限获取失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    //更新列表
    private void inflateListView(File[] files) throws IOException {
        if (files.length == 0) {//判断传入文件集合长度
            Toast.makeText(MainActivity.this, "文件夹为空", Toast.LENGTH_SHORT).show();
        } else {
            //创建一个list集合，list集合的元素是Map
            List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < files.length; i++) {
                Map<String, Object> listItem = new HashMap<String, Object>();
                //如果当前File是文件夹，使用folder图标；否则使用file图标
                if (files[i].isDirectory()) listItem.put("icon", R.drawable.file);
                else listItem.put("icon", R.drawable.txt);
                listItem.put("fileName", files[i].getName());
                //添加List
                listItems.add(listItem);
            }//for
            //创建一个SimpleAdapter
            SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems, R.layout.list_item,
                    new String[]{"icon", "fileName"}, new int[]{R.id.icon, R.id.filename});
            listpath.setAdapter(simpleAdapter);
            textpath.setText("当前路径为：" + currentParent.getCanonicalPath());
        }
    }

    //条目列表点击事件
    private void click() {
        listpath.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (currentFiles[position].isFile()) {
                    Toast.makeText(MainActivity.this, "暂不支持文件查看", Toast.LENGTH_SHORT).show();
                } else {
                    //获取 currentFiles[position] 路径下的所有文件
                    File[] tmp = currentFiles[position].listFiles();
                    if (tmp == null || tmp.length == 0) {
                        Toast.makeText(MainActivity.this, "空文件夹！",
                                Toast.LENGTH_SHORT).show();
                    }//if
                    else {
                        //获取用户单击的文件夹，设为当前的父文件夹
                        currentParent = currentFiles[position];
                        //保存当前文件夹内的全部文件和文件夹
                        currentFiles = tmp;
                        try {
                            inflateListView(currentFiles);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }//else
                }//else
            }//onItemClick
        });


    }

    //返回上层菜单
    private void onbey() {
        try {
            if (!"txt".equals(currentParent.getCanonicalPath())) {
                //获取上一层目录
                currentParent = currentParent.getParentFile();
                //列出当前目录下的所有文件
                currentFiles = currentParent.listFiles();
                //再次更新ListView
                inflateListView(currentFiles);
            } else {
                new AlertDialog.Builder(this)
                        .setIcon(R.mipmap.ic_launcher)
                        .setTitle("提示")
                        .setMessage("确定要退出吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .create()
                        .show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }//catch
    }

    private void back(){
        imageback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onbey();
            }
        });
    }
    //监听手机自带返回键
    public void onBackPressed(){
        onbey();
    }
}



